package com.tbsoft.ehr.action.staffFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tbsoft.ehr.action.BaseAction;
import com.tbsoft.ehr.constants.AuditStatus;
import com.tbsoft.ehr.constants.WorkStatus;
import com.tbsoft.ehr.login.UserInfo;
import com.tbsoft.ehr.model.Account;
import com.tbsoft.ehr.model.Agency;
import com.tbsoft.ehr.model.Contract;
import com.tbsoft.ehr.model.ContractVo;
import com.tbsoft.ehr.model.Department;
import com.tbsoft.ehr.model.ServiceCustomer;
import com.tbsoft.ehr.model.StaffInfo;
import com.tbsoft.ehr.service.contract.ContractService;
import com.tbsoft.ehr.service.staffile.StaffFileService;
import com.tbsoft.ehr.service.user.UserService;

public class StaffFileAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(StaffFileAction.class);

	//档案信息对象
	private StaffInfo staff;
	//银行账户对象
	private Account account1;
	private Account account2;

	//服务客户id
	private String serviceCustomerId;
	//机构id
	private String agencyId;
	//客户id
	private String deptId;
	
	//合同对象vo
	private ContractVo contractVo;
	
	private StaffFileService staffFileService;	
	private ContractService contractService;
	private UserService userService;
	
	//查询时用到字段：
	private Date entryDateFrom;
	private Date entryDateTo;
	//离职时候需用到的时间
	private Date currentDate;
	
	//查询结果封装
	private List<StaffInfo> staffFileLst = new ArrayList<StaffInfo>();
	
	public List<StaffInfo> getStaffFileLst() {
		return staffFileLst;
	}

	public void setStaffFileLst(List<StaffInfo> staffFileLst) {
		this.staffFileLst = staffFileLst;
	}

	public Date getEntryDateFrom() {
		return entryDateFrom;
	}

	public void setEntryDateFrom(Date entryDateFrom) {
		this.entryDateFrom = entryDateFrom;
	}

	public Date getEntryDateTo() {
		return entryDateTo;
	}

	public void setEntryDateTo(Date entryDateTo) {
		this.entryDateTo = entryDateTo;
	}	

	public StaffInfo getStaff() {
		return staff;
	}

	public void setStaff(StaffInfo staff) {
		this.staff = staff;
	}	

	public String getAgencyId() {
		return agencyId;
	}

	public void setAgencyId(String agencyId) {
		this.agencyId = agencyId;
	}

	public String getServiceCustomerId() {
		return serviceCustomerId;
	}

	public void setServiceCustomerId(String serviceCustomerId) {
		this.serviceCustomerId = serviceCustomerId;
	}	

	public String getDeptId() {
		return deptId;
	}

	public void setDeptId(String deptId) {
		this.deptId = deptId;
	}	

	public Account getAccount1() {
		return account1;
	}

	public void setAccount1(Account account1) {
		this.account1 = account1;
	}

	public Account getAccount2() {
		return account2;
	}

	public void setAccount2(Account account2) {
		this.account2 = account2;
	}

	public ContractVo getContractVo() {
		return contractVo;
	}

	public void setContractVo(ContractVo contractVo) {
		this.contractVo = contractVo;
	}

	public Date getCurrentDate() {
		this.currentDate = new Date(System.currentTimeMillis());
		return this.currentDate;
	}

	public void setCurrentDate(Date currentDate) {
		this.currentDate = currentDate;
	}

	public void setStaffFileService(StaffFileService staffFileService) {
		this.staffFileService = staffFileService;
	}

	public ContractService getContractService() {
		return contractService;
	}

	public void setContractService(ContractService contractService) {
		this.contractService = contractService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}


	public String save() {
		//获取当前用户id
		//this.staff.setUserId(readUserId());
		//通过用户邮箱对用户进行验证
		String email = this.staff.getEmail();
		if(email.isEmpty()||!email.endsWith("@tobosoft.com.cn")){
			return errorReturn("请输入合法的拓保邮箱");
		}
		String userId = email.substring(0,email.indexOf('@'));
		UserInfo ui =userService.getUser(userId);
		if(ui==null) {
			return errorReturn("该邮箱对应的用户不存在");
		}
		StaffInfo si = staffFileService.getStaffFileByUserId(userId);
		if(si!=null){
			return errorReturn("该邮箱对应的用户已存在档案信息，请检查后重试");
		}
		//设置userid
		this.staff.setUserId(userId);
		// 设置服务客户，机构，部门,若未选择服务客户，使用本部
		if (this.serviceCustomerId != null
				&& this.serviceCustomerId.length() > 0) {
			ServiceCustomer sc = new ServiceCustomer(this.serviceCustomerId);
			this.staff.setServiceCustomer(sc);
		} 
		if (this.agencyId != null && this.agencyId.length() > 0) {
			Agency ag = new Agency(this.agencyId);
			this.staff.setAgency(ag);
		}

		if (this.deptId != null && this.deptId.length() > 0) {
			Department dept = new Department(this.deptId);
			this.staff.setDepartment(dept);
		}

		if (this.account1.getAccountId() != null
				&& this.account1.getAccountId().length() > 0) {
			this.staff.getAccounts().add(this.account1);
		}
		if (this.account2.getAccountId() != null
				&& this.account2.getAccountId().length() > 0) {
			this.staff.getAccounts().add(this.account2);
		}
		this.staff.setWorkStatus(WorkStatus.WORK_ON.name());
		this.staff.setAuditStatus(AuditStatus.AUDIT_NOPASSED.name());
		
		try {
			this.staffFileService.addStaffFile(this.staff, this.getAttachFileList());
		} catch (Exception ex) {
			log.error("save error!",ex);
			return errorReturn("保存档案时出错："+ex.getMessage());
		}
		return SUCCESS;
	}	
	
	/**
	 * 根据条件查询档案
	 * @return
	 */
	public String query() {
		log.info("根据条件查询档案信息");		
		
		if(this.serviceCustomerId!=null&&this.serviceCustomerId.length()>0){			
			ServiceCustomer sc = new ServiceCustomer(this.serviceCustomerId);
			this.staff.setServiceCustomer(sc);
		}
		if(this.agencyId!=null&&this.agencyId.length()>0){
			Agency ag = new Agency(this.agencyId);
			this.staff.setAgency(ag);
		}
		if(this.deptId!=null&&this.deptId.length()>0){
			Department dept = new Department(this.deptId);
			this.staff.setDepartment(dept);
		}
		
		String entrydateFromStr=null;
		String entrydateToStr = null;
		if (this.entryDateFrom != null && this.entryDateTo != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			entrydateFromStr = sdf.format(this.entryDateFrom);
			entrydateToStr = sdf.format(this.entryDateTo);
		}
		
		int pageNum = this.getPageNum() > 0 ? this.getPageNum() - 1 : 0;
		int startIndex = pageNum * getNumPerPage();		
		int count = this.staffFileService.getStaffFileCount(staff,entrydateFromStr,entrydateToStr);
		log.info("该条件下获得数据总条数为："+count);
		setTotalCount(count);
		setPageNumShown((getNumPerPage()+count)/getNumPerPage());
		
		List<StaffInfo> tmpLst = this.staffFileService.getStaffFileByCondton(staff, entrydateFromStr, entrydateToStr,startIndex,getNumPerPage());
		staffFileLst.clear();
		if(tmpLst!=null&&tmpLst.size()>0) {
			staffFileLst.addAll(tmpLst);
		}
		return "list";
	}
	
	/**
	 * 逻辑删除
	 * @return
	 */
	public String delete(){
		if(this.staff!=null&&!this.staff.getStaffId().isEmpty()){
			try{
				this.staffFileService.deleteStaff(staff);	
				setRel("staffFile_browse");
			} catch(Exception ex){
				log.error("执行逻辑删除时出错",ex);
				return errorReturn("逻辑删除档案失败:"+ex.getMessage());
			}
		} else {
			log.info("没有需要删除的对象");
		}
		return SUCCESS;
	}
	
	/**
	 * 编辑档案
	 * 
	 * @return
	 */
	public String edit() {
		if(this.staff!=null&&this.staff.getStaffId()!=null) {
			this.staff = this.staffFileService.getStaffFileById(this.staff.getStaffId());
			if(this.staff.getAccounts().size()==2){
				this.account1 = this.staff.getAccounts().get(0);
				this.account2 = this.staff.getAccounts().get(1);		
			} else if(this.staff.getAccounts().size()==1){
				this.account1 = this.staff.getAccounts().get(0);
			}
			return "update";
		} else{
			log.info("没有需要编辑的对象");
			return "browse";
		}
	}
	
	/**
	 * 更新档案信息
	 * 
	 * @return
	 */
	public String update() {
		Agency ag = new Agency(this.agencyId);
		Department dt = new Department(this.deptId);
		this.staff.setAgency(ag);
		this.staff.setDepartment(dt);
		
		if(this.serviceCustomerId!=null&&this.serviceCustomerId.length()>0) {
			ServiceCustomer sc= new ServiceCustomer(this.serviceCustomerId);
			this.staff.setServiceCustomer(sc);
		}
		List<Account> updAccounts = new ArrayList<Account>();
		if(this.account1.notNull()){
			updAccounts.add(this.account1);
		}
		if(this.account2.notNull()){
			updAccounts.add(this.account2);
		}
		this.staff.setAccounts(updAccounts);
		//更改信息之后自动设置为未审核通过状态
		this.staff.setAuditStatus(AuditStatus.AUDIT_NOPASSED.name());
		try {			
			this.staffFileService.updateStaffFile(this.staff,this.getAttachFileList());
		} catch(Exception ex){
			log.error("update error!",ex);
			return errorReturn("更新档案信息时出错："+ex.getMessage());
		}
		//setCallbackType("closeCurrent");
		setRel("staffFile_browse");
		return SUCCESS;
	}
	
	public String beforeResignate() {
		if(this.staff!=null&&!this.staff.getStaffId().isEmpty()) {
			this.staff = this.staffFileService.getStaffFileById(this.staff.getStaffId());			
		} else {
			log.info("没有选中对象");
		}
		return "resignate";
	}
	
	/**
	 * 设置用户为离职状态
	 * @return
	 */
	public String resignate() {
		if(this.staff!=null&&this.staff.getStaffId()!=null) {
			try{
				this.staffFileService.resignatStaff(this.staff);
				setRel("staffFile_browse");
			} catch(Exception ex) {
				log.error("设置离职时出错",ex);
			}
		} 
		return SUCCESS;
	}
	
	/**
	 * 完整显示档案信息
	 * @return
	 */
	public String view() {
		if (this.staff != null && this.staff.getStaffId() != null) {
			this.staff = this.staffFileService.getStaffFileById(this.staff
					.getStaffId());
			List<Contract> contractLst = this.contractService.getContractByStaff(this.staff);
			if(contractLst.size()>0){
				this.contractVo = this.contractService.genContractInfo(contractLst);
			}
		} else {
			log.info("没有选中的对象");
		}
		return "view";
	}

	/**
	 * 档案审核
	 * @return
	 */
	public String audit() {
		if (this.staff != null && this.staff.getStaffId() != null) {
			try{				
				this.staffFileService.auditStaff(this.staff);
				setRel("staffFile_browse");
			} catch(Exception ex){
				log.error("更改审核状态时出错",ex);
				return errorReturn("更改审核状态时出错:"+ex.getMessage());
			}
		} else{
			log.info("没有选中的对象");
		}
		return SUCCESS;
	}
		
}
